<script setup lang="ts">
  import HeaderView from '@/layouts/modules/header/HeaderView.vue'
  import { ref, onMounted } from 'vue'
  import { router } from '@/router'
  import { useRoute } from 'vue-router'
  import { getSearchPageProducts,getSearchPageBrands,getSameCatalogues } from '@/api'
  import { sortByPriceAsc, sortByPriceDesc } from '@/utils'

  //输入内容
  const state = ref('')
  //true，升序，false，降序
  const sortValue = ref(true)

  const currentPage = ref(1)
  const pageSize = ref(30)
  const small = ref(false)
  const background = ref(false)
  const disabled = ref(false)
  const total = ref(0)

  const selectBrand = ref(0)
  const selectType = ref(0)
  const selectPrice = ref(null)

  //品牌
  const brands = ref([
    { id:'32', name:'品牌1'},
    { id:'32', name:'品牌2'},
    { id:'32', name:'品牌3'},
    { id:'32', name:'品牌4'},
    { id:'44', name:'品牌5'},
    { id:'44', name:'品牌6'},
    { id:'44', name:'品牌7'},
    { id:'44', name:'品牌8'},
    { id:'44', name:'品牌9'},
    { id:'44', name:'品牌10'}
  ])
  //材质
  const types = ref( [
    {id:37,name:'衣物服饰'},
    {id:38,name:'数码电子'},
    {id:39,name:'家居用品'},
    {id:40,name:'母婴用品'},
    {id:41,name:'美妆个护'},
    {id:42,name:'图书音像'},
    {id:43,name:'宠物用品'},
    {id:44,name:'食品饮料'}
  ])
  //价格
  const prices = ref([
    { id:'1', name:'0-100'},
    { id:'2', name:'100-200'},
    { id:'3', name:'200-300'},
    { id:'4', name:'300-400'},
    { id:'5', name:'400-500'},
    { id:'6', name:'500-600'},
    { id:'7', name:'600-700'},
    { id:'8', name:'700-800'},
    { id:'9', name:'800-900'},
    { id:'10', name:'900-1000'},
    { id:'11', name:'1000+'}
  ])

  const results = ref([
    { id:'',
      name:'',
      img:'',
      type:"",
      price:undefined
    }
  ])


  interface LinkItem {
    value: string
    link: string
  }

  const links = ref<LinkItem[]>([])

  const loadAll = () => {
    return [
      { value: 'vue', link: 'https://github.com/vuejs/vue' },
      { value: 'element', link: 'https://github.com/ElemeFE/element' },
      { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
      { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
      { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
      { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
      { value: 'babel', link: 'https://github.com/babel/babel' },
    ]
  }

  let timeout: ReturnType<typeof setTimeout>
  const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
    const results = queryString
      ? links.value.filter(createFilter(queryString))
      : links.value

    clearTimeout(timeout)
    timeout = setTimeout(() => {
      cb(results)
    }, 3000 * Math.random())
  }
  const createFilter = (queryString: string) => {
    return (restaurant: LinkItem) => {
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }

  const handleSelect = (item: Record<string, any>) => {
    console.log(item)
  }


  //确定查询，发送搜索结果
  const handleSearch = () => {
    getSearchPageProduct()
  }

  onMounted(() => {
    selectType.value = parseInt(useRoute().query.type+'')
    getLocalCatalogues()
    links.value = loadAll()
    getSearchPageProduct()
  })

  const getLocalCatalogues = () => {
    getSameCatalogues(selectType.value).then(({data}) => {
      types.value = data
    })
  }

  //搜索商品
  const getSearchPageProduct = () => {
    getSearchPageProducts({
      page: currentPage.value,
      pageSize: pageSize.value,
      name: state.value,
      price: selectPrice.value,
      classId: selectType.value,
      brandId: selectBrand.value
    }).then(res => {
      results.value = res.data.records
      total.value = res.data.total
      currentPage.value= res.data.current
    }, err => {
      console.log(err)
    })
    getSearchBrands()
  }

  //获取品牌
  const getSearchBrands = () => {
    getSearchPageBrands(selectType.value).then(({data}) => {
      brands.value = data
    }, err => {
      console.log(err)
    })
  }

  //跳转到商品详情页
  const changePage = (ids:string,type:string) => {
    router.push({path:'/product',query:{name:ids,type:type}})
  }


  //价格排序
  const resultSort = () => {
    if(sortValue.value){
      sortByPriceAsc(results)
    }else{
      sortByPriceDesc(results)
    }
  }

</script>

<template>
  <HeaderView />
  <div class="search-view">
    <div class="search-line" style="margin-top: 20px;">
      <img src="@/assets/img/fish.svg" style="width: 100px;position: relative;" alt=""/>
      <el-autocomplete
        v-model="state"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入内容"
        @select="handleSelect"
        class="search-input"
        clearable
        style="width: 30%;top: 30%;min-width: 200px;position:absolute;left: 50%;transform: translateX(-50%) translateY(-30%);">
        <template #append>
          <el-button  @click="handleSearch">
            <el-image src="src/assets/img/search.svg" style="width: auto;height: 20px;" alt=""/>
          </el-button>
        </template>
      </el-autocomplete>
      <a class="carts" href="/carts">购物车</a>
    </div>
    <el-divider />

    <div class="search-condition" style="margin-top: 20px;">
      <div class="condition-items">
        <div class="condition-label"><p>商品类型:</p></div>
        <el-radio-group v-model="selectType" size="large" class="condition-item" @change="getSearchPageProduct">
          <el-radio-button class="condition-item-detail" value="0" >无</el-radio-button>
          <el-radio-button class="condition-item-detail" v-for="(item,index) in types" :key="index" :value="item.id" >{{item.value}}</el-radio-button>
        </el-radio-group>
      </div>
      <div class="condition-items">
        <div class="condition-label"><p>品牌:</p></div>
        <el-radio-group v-model="selectBrand" size="large" class="condition-item" @change="getSearchPageProduct">
          <el-radio-button class="condition-item-detail" value="0" >无</el-radio-button>
          <el-radio-button class="condition-item-detail" v-for="(item,index) in brands" :key="index" :value="item.id" >{{item.name}}</el-radio-button>
        </el-radio-group>
      </div>
      <div class="condition-items">
        <div class="condition-label"><p>价格:</p></div>
        <el-radio-group v-model="selectPrice" size="large" class="condition-item" @change="getSearchPageProduct">
          <el-radio-button class="condition-item-detail" value="null" >无</el-radio-button>
          <el-radio-button class="condition-item-detail" v-for="(item,index) in prices" :key="index" :value="item.name">{{item.name}}</el-radio-button>
        </el-radio-group>

      </div>
    </div>

    <el-divider />
    <p class="result-sort">
      <span>排序条件:</span>
      <span class="sort-condition">价格&emsp;<el-switch
        v-model="sortValue"
        inline-prompt
        active-text="升"
        inactive-text="降"
        @change="resultSort"
      /></span>
    </p>
    <div class="search-result" style="margin-top: 20px;">
      <div class="result-items">
        <el-card v-for="(item,index) in results" :key="index" style="width: 200px;margin-left: 10px;" class="result-card" @click="changePage(item.id,item.type)">
            <el-image :src="item.img" alt="" class="result-img" fit="contain"/>
            <p class="result-name">{{item.name}}</p>
            <p class="result-price">￥{{item.price}}</p>
        </el-card>
      </div>
    </div>
    <div class="demo-pagination-block"  style="clear: both;float: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[30, 60, 90, 120]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getSearchPageProduct"
        @current-change="getSearchPageProduct"
      />
    </div>
  </div>
</template>

<style scoped>
.search-view{
  height: auto;
  width: 80vw;
  min-width: 800px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.search-line{
  height: 100px;
  width: 100%;
  position: relative;
}

.search-input .el-input__inner{
  height: 200px;
}

.carts{
  position: relative;
  top: 30%;
  left: 70%;
  float: left;
  width: 100px;
  line-height: 50px;
  transform: translateY(-30%);
  text-align: center;
  background-color: #90e2f5;
  color: red;
}

.condition-items{
  margin-top: 10px;
  display: flex;
}

.condition-item{
  margin-left: 10px;
  width: 100%;
  height: 50px;
  overflow-y: scroll;
}

.condition-label{
  min-width: 100px;
  min-height: 30px;
  height: auto;
  background-color: #bbefee;
}

.condition-label p{
  text-align: center;
  margin-top: 10px;
}

.condition-item-detail{
  margin-bottom: 4px;
}

.result-sort{
  height: 20px;
}

.sort-condition{
  margin-left: 15px;
}


.search-result{
  width: 100%;
  display: flex;
}


.result-card{
  float: left;
  width: 20%;
  min-height: 350px;
  min-width: 240px;
  margin-bottom: 20px;
  margin-right: 19px;
}

.result-img{
  height: 220px;
  width: 220px;
}

.result-name{
  margin-top: 20px;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.result-price{
  text-align: center;
  margin-top: 10px;
  color: red;
}


</style>